/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.cas.support.user.userregistry.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.qloudgen.sec.cas.support.user.services.User;
import org.qloudgen.sec.cas.support.user.services.UsersManager;

import org.qloudgen.sec.cas.support.user.services.UserDetail;
import org.qloudgen.sec.cas.support.user.services.UserDetailManager;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public final class ManageUserSimpleFormController extends SimpleFormController {
	private static final Logger logger = LoggerFactory.getLogger(ManageUserSimpleFormController.class);

    /** Instance of ServiceRegistryManager. */
    @NotNull
    private final UsersManager usersManager;

    @NotNull
    private final UserDetailManager userDetailManager;

    public ManageUserSimpleFormController(final UsersManager usersManager,final UserDetailManager userDetailManager) {
        this.usersManager = usersManager;
        this.userDetailManager = userDetailManager;
    }

    /**
     * 
     */
    @Override
    protected void initBinder(final HttpServletRequest request,
            final ServletRequestDataBinder binder) throws Exception {        
        /*final List<UserDetail> list = this.userDetailManager.getCanDeleteUserDetail(); 
        String[] requiredFields = null;
        int i = 0;
        for (UserDetail detail : list){
        	  if (detail.getColRequired() == true && (detail.getColName().equals("name") || detail.getColName().equals("password"))){
        	  	   requiredFields[i] = detail.getColName();
        	  	    i++;
        	  	 }
            if (detail.getColRequired() == true && !detail.getColName().equals("name") && !detail.getColName().equals("password")){
            	    requiredFields[i] = "col['"+detail.getColName()+"']";
            	    i++;
            }
        }*/
        
        binder.setRequiredFields(new String[]{"name","password"});
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    /**
     *
     */
    @Override
    protected ModelAndView onSubmit(final HttpServletRequest request,
            final HttpServletResponse response, final Object command,
            final BindException errors) throws Exception {

        User user = (User) command;
        final List<UserDetail> list = this.userDetailManager.getCanDeleteUserDetail(); 
        user.setProperty(list);
        this.usersManager.save(user);
        logger.debug("Saved changes to user " + user);

        final ModelAndView modelAndView = new ModelAndView(new RedirectView(
                "manageUser.html#" + user.getId(), true));
        modelAndView.addObject("action", "add");
        modelAndView.addObject("id", user.getId());

        return modelAndView;
    }

    @Override
    protected Object formBackingObject(final HttpServletRequest request)
            throws Exception {
        final String id = request.getParameter("id");

        if (!StringUtils.hasText(id)) {
            
            final Object user;
            if (this.getCommandClass() != null) {
                user = this.createCommand();
            } else {
                user = new User();
            }
            logger.debug("Created new user " + user.toString());
            return user;
        }

        final User user = this.usersManager.findUserBy(id);

        if (user != null) {
        	  final List<UserDetail> list = this.userDetailManager.getCanDeleteUserDetail(); 
            user.setProperty(list);
            for ( UserDetail detail : list ){
            	  if ( !user.getCol().containsKey( detail.getColName() ) ){
            	  	  user.getCol().put( detail.getColName(), "" );
            	  }
            }
            logger.debug("current user is :" + user);
        } else {
            logger.debug("Invalid user id specified.");
        }

        return user;
    }

    /**

     */
    @Override
    //@RequestMapping(value = "/show", method = RequestMethod.GET)
    protected Map<?, ?> referenceData(final HttpServletRequest request) throws Exception {
       
        final List<UserDetail> list = this.userDetailManager.getCanDeleteUserDetail();  
        
        final String id = request.getParameter("id");
        
        final Map<String, Object> model = new HashMap<String, Object>();
        
        HashMap<String,String> colKeyValue = new HashMap<String,String>();
        
        for ( UserDetail userDetail : list ){
        	colKeyValue.put( userDetail.getColName() ,"" );
        }
        
        if (id == null){
			        User user = new User();
			        user.setCol(colKeyValue);
			        
			        user.setProperty(list);
			        model.put("user",user);
        }
        model.put("pageTitle", getFormView());
        model.put("commandName", getCommandName());
        return model;
    }
}
